package com.wendy.controller;

import com.wendy.model.User;
import com.wendy.service.UserService;
import com.wendy.web.response.ResponseWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author zhuwending
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseWrapper login(HttpServletRequest request) {
        return userService.login(request);
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (null == user) {
            model.addAttribute("msg", "登录失效");
            return "login";
        }
        return "index";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(HttpServletRequest request, User user, Model model) {
        ResponseWrapper response = userService.register(user);
        if (!response.isSuccess()) {
            model.addAttribute("msg", response.getMsg());
            return "register";
        }
        user = userService.selectUserForLogin(user.getUsername(), user.getPassword());
        HttpSession session = request.getSession();
        session.setAttribute("user", user);
        session.setMaxInactiveInterval(1000 * 60 * 30);
        return "menu";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public ResponseWrapper uploadFile(HttpServletRequest request, MultipartFile file) {
        return userService.uploadPortrait(request, file);
    }

    @RequestMapping(value = "/compress", method = RequestMethod.GET)
    public String compressPicture(HttpServletRequest request) {
        try {
            userService.compressPicture(request);
        } catch (Exception e) {
            return "500";
        }
        return "menu";
    }
}
